<template>
  <div>
    <BasicModal
      @register="register"
      :title="title"
      width="800px"
      :destroyOnClose="true"
      :canFullscreen="false"
      :showOkBtn="false"
      :showCancelBtn="false"
    >
      <BasicForm
        @register="registerForm"
        :show-reset-button="showBtn"
        :show-submit-button="showBtn"
      >
        <template #imageUrls="{ model, field }">
          <div class="img-list">
            <Image
              v-for="(item, index) in model[field]"
              :key="index"
              :src="item"
              width="128px"
              height="128px"
              style="object-fit: cover"
            />
          </div>
        </template>
        <template #productPriceInfo>
          <Table :dataSource="productPriceInfo" :columns="productSpecInfo" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'imgUrl'">
                <Image :src="record[column.key]" width="48px" height="48px"></Image>
              </template>
              <template v-else>
                <Input :value="record[column.key]" disabled />
              </template>
            </template>
          </Table>
        </template>
        <template #CommissionSharing>
          <span>固定佣金</span>
        </template>
        <template #commissionRate>
          <span
            >比例{{ formData?.commissionRate }}%（预计{{
              formData?.productMinCommissionPrice
            }}</span
          ><span v-if="formData?.productMinCommissionPrice !== formData?.productMaxCommissionPrice"
            >~{{ formData?.productMaxCommissionPrice }}</span
          >元）
        </template>
        <template #discountInfo="{ model, field }">
          <div v-if="model[field]?.length" style="display: flex; flex-direction: column; gap: 16px">
            <div
              v-for="(item, index) in model[field]"
              :key="index"
              style="display: flex; gap: 10px"
            >
              <div style="width: 200px; text-align: right"> {{ item.levelName }}： </div>
              <span>{{ item.discount }}折</span>
            </div>
          </div>
        </template>
        <template #logisticsMode="{ model, field }">
          <div v-if="model[field]" class="logistics-mode">
            <Input
              disabled
              :value="
                dicts.logisticsMode.find((item) => item.dictValue == model[field].logisticsMode)
                  ?.dictLabel
              "
            />
            <div v-if="model[field].logisticsMode == LogisticsModeEnum.TO_STORE" class="store-box">
              <h2
                >{{
                  `${
                    dicts.logisticsMode.find((item) => item.dictValue == model[field].logisticsMode)
                      ?.dictLabel
                  }(已选择${model[field].storeDtoList.length}个门店) `
                }}
              </h2>
              <div class="store-list">
                <div
                  v-for="(item, index) in model[field].storeDtoList"
                  :key="index"
                  class="store-info"
                >
                  <Image :src="item.logoUrl" width="50px" height="50px"></Image>
                  <div class="store-name-address">
                    <span class="name">{{ item.name }}</span>
                    <span class="address">{{ item.address }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div
              v-if="model[field].logisticsMode == LogisticsModeEnum.NO_EXPRESS"
              style="background-color: #f2f3f5; padding: 20px; margin-top: 10px"
            >
              <div v-for="item in model[field].formItemInfo" :key="item.id" style="margin: 10px 0">
                <div style="display: flex; gap: 16px">
                  <div style="width: 160px; color: #4e5969; font-size: 14px; line-height: 32px">{{
                    item.showName
                  }}</div>
                  <div>
                    <Input
                      disabled
                      :placeholder="item.itemTypeId == ItemTypeIdEnum.Select ? '选择项' : '填写项'"
                    />
                    <template v-if="item.itemTypeId == ItemTypeIdEnum.Select">
                      <div
                        v-for="({ words }, index) in item.customFormItemAnswerList"
                        :key="index"
                        style="display: flex; margin: 10px 0"
                      >
                        <Radio disabled></Radio>
                        <span> {{ words }}</span>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template #afterSaleContactsInfo="{ model, field }">
          <div v-for="item in model[field]" :key="item.id" style="display: flex; gap: 5px">
            <span>{{ item.userName }}</span>
            <span>{{ item.phone }}</span>
          </div>
        </template>
        <template #purchaseLimitType="{ model, field }">
          <div v-if="model[field]" class="purchase-limit">
            <Input
              disabled
              :value="
                dicts.purchaseLimit.find((item) => item.dictValue == model[field].purchaseLimitType)
                  ?.dictLabel
              "
            />
            <div v-if="model[field].purchaseLimitType == PurchaseLimit.YES">
              <div>
                <div>最小限制：</div>
                <Input :value="model[field].minNum" disabled />
              </div>
              <div>
                <div>最大限制：</div>
                <Input :value="model[field].maxNum" disabled />
              </div>
            </div>
          </div>
        </template>
        <template #productDesc="{ model, field }">
          <div v-if="model[field]?.length" class="hb-p-3">
            <div class="hb-flex hb-gap-2 hb-justify-center hb-items-center hb-mb-2">
              <div class="hb-w-6 hb-h-1 hb-bg-balck"></div>
              <text class="hb-text-4">产品详情</text>
              <div class="hb-w-6 hb-h-1 hb-bg-balck"></div>
            </div>
            <div class="hb-flex hb-flex-col hb-gap-2 hb-justify-center hb-items-center">
              <div v-for="({ moduleType, fileUrls, text }, index) in model[field]" :key="index">
                <template v-if="moduleType == ModuleTypeEnum.LargeImage">
                  <div v-for="(url, i) in fileUrls" :key="i">
                    <Image
                      :src="url"
                      width="351px"
                      height="160px"
                      border-radius="8px"
                      style="object-fit: cover"
                    ></Image>
                  </div>
                </template>
                <div
                  v-else-if="moduleType == ModuleTypeEnum.SmallImage"
                  class="hb-grid hb-grid-cols-3 hb-gap-2"
                >
                  <div v-for="(url, i) in fileUrls" :key="i">
                    <Image
                      :src="url"
                      border-radius="8px"
                      width="111px"
                      height="111px"
                      style="object-fit: cover"
                    ></Image>
                  </div>
                </div>
                <div v-else-if="moduleType == ModuleTypeEnum.Video">
                  <video
                    id="video"
                    :src="fileUrls![0]"
                    class="hb-w-87 hb-rounded-lg hb-h-56"
                    muted
                    controls
                  ></video>
                </div>
                <div
                  v-else-if="moduleType == ModuleTypeEnum.Text"
                  class="hb-text-4 hb-leading-5 hb-w-87"
                  style="white-space: break-spaces"
                >
                  {{ text }}
                </div>
              </div>
            </div>
          </div>
        </template>
      </BasicForm>
    </BasicModal>
    <Modal
      title="审核驳回"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleReview"
      :z-index="99999"
      :centered="true"
    >
      <div style="padding: 20px">
        <Textarea
          v-model:value="content"
          placeholder="请输入驳回原因"
          :auto-size="{ minRows: 10, maxRows: 20 }"
        />
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { ref } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import Dictionary from '@/utils/dictionary';
  import { Image, Input, Modal, Textarea, Radio, Table } from 'ant-design-vue/es';
  import {
    LogisticsModeEnum,
    ModuleTypeEnum,
    ProductType,
    PurchaseLimit,
    ReviewStatus,
  } from '@/enums/productManage';
  import { getProductLibDetail, review } from '@/api/hby/productManage/index';
  import { IProductDetail, IProductPriceInfo, IProductResult } from '@/api/hby/productManage/type';
  import { ItemTypeIdEnum } from '@/enums/customFormEnum';


  const title = ref('产品详情');
  const { createMessage } = useMessage();
  const dicts = Dictionary.getLocalMulti(['productType', 'logisticsMode', 'purchaseLimit']);

  const emit = defineEmits(['reload', 'register']);

  const showBtn = ref(false);
  const formData = ref<IProductDetail>();
  const visible = ref(false);
  const confirmLoading = ref(false);
  const content = ref('');

  const handleReview = async () => {
    try {
      await review({
        id: formData.value!.id!,
        reviewStatus: ReviewStatus.Rejected,
        reviewContent: content.value,
      });
      createMessage.success({ content: '已驳回申请' });
      closeModal();
      emit('reload');
    } finally {
      visible.value = false;
      confirmLoading.value = false;
      content.value = '';
    }
  };

  const [registerForm, { setProps, setFieldsValue, updateSchema }] = useForm({
    schemas: [
      {
        field: 'proType',
        component: 'Divider',
        label: '产品类型',
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productBaseInfo.productType',
        component: 'RadioGroup',
        label: '平台类型：',
        defaultValue: dicts.productType[0]?.dictValue,
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
        componentProps: {
          options: dicts.productType.map((v) => ({ label: v.dictLabel, value: v.dictValue })),
        },
      },
      {
        field: 'info',
        component: 'Divider',
        label: '基本信息',
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productBaseInfo.productName',
        component: 'Input',
        label: '产品名称：',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'productBaseInfo.imageUrls',
        component: 'Input',
        slot: 'imageUrls',
        dynamicDisabled: true,
        label: '产品主图：',
        colProps: {
          span: 20,
        },
      },
      {
        field: 'productCategoryName',
        component: 'Input',
        label: '产品类目：',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'tenantCategoryName',
        component: 'Input',
        label: '产品分组：',
        dynamicDisabled: true,
        show: formData.value?.sourceType === 2,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'price',
        component: 'Divider',
        label: '价格库存：',
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productPriceInfo',
        component: 'Input',
        label: '',
        slot: 'productPriceInfo',
        dynamicDisabled: true,
        colProps: {
          span: 24,
          style: 'padding-left:120px',
        },
      },
      {
        field: 'distributionCommission',
        component: 'Divider',
        label: '分销佣金',
        dynamicDisabled: true,
        colProps: {
          span: 24,
        },
      },

      {
        field: 'CommissionSharing',
        component: 'Input',
        label: '分佣方式：',
        slot: 'CommissionSharing',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'commissionRate',
        component: 'Input',
        label: '分销佣金：',
        slot: 'commissionRate',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'memberDiscount',
        component: 'Divider',
        label: '会员折扣',
        show: !!formData.value?.productMemberDiscountMapInfo?.length,
        dynamicDisabled: true,
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productMemberDiscountMapInfo',
        component: 'Input',
        label: '',
        slot: 'discountInfo',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },

      {
        field: 'set',
        component: 'Divider',
        label: '其它设置：',
        dynamicDisabled: true,
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productOtherInfo',
        component: 'Input',
        label: '物流方式：',
        slot: 'logisticsMode',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'afterSaleContactsInfo',
        component: 'Input',
        label: '售后联系人：',
        slot: 'afterSaleContactsInfo',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'productOtherInfo',
        component: 'Input',
        slot: 'purchaseLimitType',
        label: '购买限制：',
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
        componentProps: {
          placeholder: '请选择购买限制',
        },
      },
      {
        field: 'productOtherInfo.deliveryDesc',
        component: 'Input',
        label: '发货时效：',
        show: formData.value?.productBaseInfo.productType != ProductType.CouponVerification,
        dynamicDisabled: true,
        colProps: {
          span: 20,
        },
      },
      {
        field: 'detail',
        component: 'Divider',
        label: '产品详情',
        dynamicDisabled: true,
        show: !!formData.value?.productDesc.length,
        colProps: {
          span: 24,
        },
      },
      {
        field: 'productOtherInfo.productDesc',
        component: 'Input',
        slot: 'productDesc',
        label: '',
        colProps: {
          span: 24,
        },
      },
    ],
    autoFocusFirstItem: true,
    actionColOptions: {
      span: 24,
    },
    labelWidth: 200,
    baseColProps: { span: 18 },
    submitButtonOptions: {
      text: '审核通过',
      onClick: async function () {
        try {
          setProps({
            submitButtonOptions: {
              loading: true,
            },
          });
          await review({ id: formData.value!.id, reviewStatus: ReviewStatus.Approved });

          createMessage.success({ content: '已通过申请' });
          closeModal();
          emit('reload');
        } finally {
          setProps({
            submitButtonOptions: {
              loading: false,
            },
          });
        }
      },
    },
    resetButtonOptions: {
      text: '驳回',
      onClick: function () {
        visible.value = true;
        return;
      },
    },
    resetFunc: async function () {
      return Promise.reject();
    },
  });
  const productPriceInfo = ref<IProductPriceInfo[]>([]);
  const productSpecInfo = ref<any>([]);
  const [register, { closeModal }] = useModalInner(
    async (data: { type: number; row: IProductResult }) => {
      showBtn.value = data.type == 1 ? false : true;

      const res = await getProductLibDetail(data.row.id);

      const productDesc = res.productOtherInfo?.productDesc;

      if (productDesc) {
        res.productOtherInfo!.productDesc = JSON.parse(productDesc as string);
      }
      formData.value = res;
      formData.value.id = data.row.id;
      productPriceInfo.value = formData.value.productPriceInfo.map((item) => {
        if (!item.imgUrl) item.imgUrl = formData.value?.productBaseInfo.imageUrls[0];
        return item;
      });
      productSpecInfo.value = [
        {
          title: formData.value.productSpecInfo[0].specName,
          dataIndex: 'specCombinationName',
          key: 'specCombinationName',
        },
        {
          title: '价格',
          dataIndex: 'salePrice',
          key: 'salePrice',
        },
        {
          title: '库存',
          dataIndex: 'stockNum',
          key: 'stockNum',
        },
        {
          title: '图片',
          dataIndex: 'imgUrl',
          key: 'imgUrl',
        },
      ];
      setFieldsValue(res);
      updateSchema({
        field: 'productOtherInfo.deliveryDesc',
        show: formData.value?.productBaseInfo.productType != ProductType.CouponVerification,
      });
      updateSchema({
        field: 'productBaseInfo.productType',
        defaultValue: formData.value.productBaseInfo.productType,
        componentProps: {
          options: dicts.productType.map((v) => ({ label: v.dictLabel, value: v.dictValue })),
        },
      });
      updateSchema({
        field: 'memberDiscount',
        show: !!formData.value?.productMemberDiscountMapInfo?.length,
      });
      updateSchema({
        field: 'detail',
        show: !!formData.value?.productDesc.length,
      });
    },
  );
</script>

<style lang="less" scoped>
  .img-list {
    display: grid;
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
  }

  .logistics-mode {
    .store-box {
      h2 {
        margin: 10px 0;
        font-weight: 600;
      }

      .store-list {
        display: flex;
        flex-direction: column;
        gap: 20px;

        .store-info {
          display: flex;
          gap: 10px;
          align-items: center;

          .store-name-address {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .name {
              font-weight: 600;
              font-size: 16px;
            }

            .address {
              font-size: 12px;
              color: #d1d1d1;
            }
          }
        }
      }
    }
  }

  .detail {
    padding: 12px;
  }

  .hb-p-3 {
    padding: 12px;
  }

  .hb-flex {
    display: flex;
  }

  .hb-gap-2 {
    gap: 8px;
  }

  .hb-justify-center {
    justify-content: center;
  }

  .hb-items-center {
    align-items: center;
  }

  .hb-mb-2 {
    margin-bottom: 8px;
  }

  .hb-w-6 {
    width: 24px;
  }

  .hb-h-1 {
    height: 4px;
  }

  .hb-bg-balck {
    background: #333;
  }

  .hb-text-4 {
    font-size: 16px;
  }

  .hb-h-8 {
    height: 32px;
  }

  .hb-flex-col {
    flex-direction: column;
  }

  .hb-gap-2 {
    gap: 8px;
  }

  .hb-grid {
    display: grid;
  }

  .hb-grid-cols-3 {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .hb-w-87 {
    width: 375px;
  }

  .hb-rounded-lg {
    border-radius: 8px;
  }

  .hb-h-56 {
    height: 224px;
  }

  .hb-text-4 {
    font-size: 16px;
  }

  .hb-leading-5 {
    line-height: 22px;
  }
</style>
